import axios from 'axios';
import { HttpConfigSource } from './config';
const instances = new Map();
export const http = {
	development: false,
	method: {
		GET: 'get',
		POST: 'post',
		PUT: 'put',
		PATCH: 'patch',
		DELETE: 'delete',
		OPTIONS: 'options',
		HEAD: 'head'
	},
	create(config, callback) {
		const httpConfig = HttpConfigSource.merge(config);
		const instance = axios.create(config);
		if (callback) {
			callback(instance);
		}
		instances.set(httpConfig.id, instance);
		if (this.development && process.env.NODE_ENV === 'development') {
			this.showMemory();
		}
		return httpConfig.id;
	},
	destroy(id) {
		const res = instances.delete(id);
		if (this.development && process.env.NODE_ENV === 'development') {
			this.showMemory();
		}
		return res;
	},
	request(config) {
		let instance = axios;
		if (instances.get(config.id)) {
			instance = instances.get(config.id) || axios;
		} else {
			console.warn(
				`unable to find the value of ${config.id.toString} in instances.`
			);
		}
		return instance.request(config);
	},
	all(configs) {
		return new Promise((resolve, reject) => {
			axios
				.all(configs.map(config => this.request(config)))
				.then(
					axios.spread((...results) => {
						resolve(results);
					})
				)
				.catch(error => {
					reject(error);
				});
		});
	},
	raw() {
		return axios;
	},
	showMemory() {
		if (instances.size === 0) {
			console.warn('no memory');
		} else {
			console.warn('start show memory');
			instances.forEach((value, key) => {
				console.log(key.toString());
			});
			console.warn('end show memory');
		}
	}
};
